import { Component, EventTouch, Input, input, misc, v2, Vec2, _decorator } from 'cc';

const { ccclass } = _decorator;

export type InputData = { direction: Vec2; angle: number };

@ccclass('Joystick')
export default class Joystick extends Component {
	private touchPoint: Vec2 = v2();
	private inputData: InputData | null = null;

	start() {
		input.on(Input.EventType.TOUCH_START, this.onTouchStart, this);
		input.on(Input.EventType.TOUCH_MOVE, this.onTouchMove, this);
		input.on(Input.EventType.TOUCH_END, this.onTouchEnd, this);
	}

	private onTouchStart(event: EventTouch) {
		event.getLocation(this.touchPoint);
	}

	private onTouchEnd(event: EventTouch) {
		this.inputData = null;
	}

	private onTouchMove(event: EventTouch) {
		const move: Vec2 = event.getLocation().subtract(this.touchPoint);
		this.inputData = { direction: move.normalize(), angle: misc.radiansToDegrees(Math.atan2(move.y, move.x)) - 90 };
	}

	public getInput(): InputData {
		return this.inputData;
	}
}
